package com.example.capsule.repository;

import com.example.capsule.entity.Capsule;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface CapsuleRepository extends JpaRepository<Capsule, Long> {

    Optional<Capsule> findById(Long id);

    List<Capsule> findByIsUnlockedTrue();

    List<Capsule> findByIsUnlockedFalse();


    boolean existsById(Long id);

    List<Capsule> findAll();

    // 用户创建的胶囊
    List<Capsule> findBySenderPhoneOrderByCreatedAtDesc(String senderPhone);

    // 用户收到的胶囊
    List<Capsule> findByRecipientPhoneOrderByCreatedAtDesc(String recipientPhone);

    // 公开的已解锁胶囊（排序）
    List<Capsule> findByIsPublicTrueAndIsUnlockedTrueOrderByCreatedAtDesc();

    // 公开的已解锁胶囊（无排序）
    List<Capsule> findByIsPublicTrueAndIsUnlockedTrue();

    // 用户创建的已解锁胶囊
    List<Capsule> findBySenderPhoneAndIsUnlockedTrue(String senderPhone);

    // 用户收到的已解锁胶囊
    List<Capsule> findByRecipientPhoneAndIsUnlockedTrue(String recipientPhone);

    // 统计方法
    long countBySenderPhone(String senderPhone);
    long countByRecipientPhone(String recipientPhone);
    long countBySenderPhoneAndIsUnlockedTrue(String senderPhone);
    long countBySenderPhoneAndIsUnlockedFalse(String senderPhone);
    long countByRecipientPhoneAndIsUnlockedTrue(String recipientPhone);
    long countByRecipientPhoneAndIsUnlockedFalse(String recipientPhone);

    // 搜索方法
    @Query("SELECT c FROM Capsule c WHERE c.senderPhone = :phone AND " +
            "(c.title LIKE %:titleKeyword% OR c.content LIKE %:contentKeyword%) " +
            "ORDER BY c.createdAt DESC")
    List<Capsule> findBySenderPhoneAndTitleContainingOrContentContaining(
            @Param("phone") String phone,
            @Param("titleKeyword") String titleKeyword,
            @Param("contentKeyword") String contentKeyword);

    // 根据分享令牌查找
    Optional<Capsule> findByShareToken(String shareToken);

    // 新增：根据发送者和公开状态查找
    List<Capsule> findBySenderPhoneAndIsPublic(String senderPhone, Boolean isPublic);

    // 新增：根据接收者和解锁状态查找
    List<Capsule> findByRecipientPhoneAndIsUnlocked(String recipientPhone, Boolean isUnlocked);

    // 新增：根据公开状态查找
    List<Capsule> findByIsPublic(Boolean isPublic);

    // 修改查询方法，包含未发送通知的检查
    @Query("SELECT c FROM Capsule c WHERE c.unlockTime <= :currentTime AND c.isUnlocked = false")
    List<Capsule> findExpiredCapsules(@Param("currentTime") LocalDateTime currentTime);
}